package com.paomi.client.service;

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;


import com.paomi.client.MyApplication;
import com.paomi.client.R;
import com.paomi.client.base.BaseMvpActivity;
import com.paomi.client.bean.AppVersionBean;
import com.paomi.client.net.Api;
import com.paomi.client.net.Constants;
import com.paomi.client.widget.RxToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 版本更新控制的服务
 * Created by admin on 2017/12/28.
 */
public class AppVersionService extends Service {
    private boolean isRun = false;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("AppVersionService", "onStartCommand");
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (intent == null) {
            //启动定位
            isRun = true;
            Api.getInstanceService(Constants.BASE_URL).getAppVersionMessage("1").enqueue(new Callback<AppVersionBean>() {
                @Override
                public void onResponse(Call<AppVersionBean> call, Response<AppVersionBean> response) {
                    if(response.body().getReturnData()!=null){
                        EventBus.getDefault().post(response.body().getReturnData());
                    }else{
                        EventBus.getDefault().post(getResources().getString(R.string.update_no));
                    }
                }

                @Override
                public void onFailure(Call<AppVersionBean> call, Throwable t) {
                    if( getNetworkType()==0){
                        EventBus.getDefault().post(getResources().getString(R.string.net_null));
                    }else{
                        EventBus.getDefault().post("请求失败");
                    }

                }
            });
            return START_STICKY;//自动重启
        } else {
            boolean isClose = intent.getBooleanExtra("close", false);
            if (isClose) {
                isRun = false;
                this.stopSelf();
            } else {
                if (isRun) {
                    return START_STICKY;
                } else {
                    //启动定位
                    isRun = true;
                    Api.getInstanceService(Constants.BASE_URL).getAppVersionMessage("1").enqueue(new Callback<AppVersionBean>() {
                        @Override
                        public void onResponse(Call<AppVersionBean> call, Response<AppVersionBean> response) {
                            new Handler().postDelayed(new Runnable() {
                                public void run() {
                                    if(response.body()!=null){
                                        if(response.body().getReturnData()!=null){
                                            EventBus.getDefault().post(response.body().getReturnData());
                                        }else{
                                            EventBus.getDefault().post(getResources().getString(R.string.update_no));
                                        }
                                    }else{
                                        AppVersionService.this.stopSelf();
                                    }
                                }
                            }, 100);
                        }

                        @Override
                        public void onFailure(Call<AppVersionBean> call, Throwable t) {
                            if( getNetworkType()==0){
                                EventBus.getDefault().post(getResources().getString(R.string.net_null));
                            }else{
                                EventBus.getDefault().post("请求失败");
                            }
                        }
                    });
                }
            }
        }
        return START_STICKY;//自动重启
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("AppVersionService", "onDestroy");
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe
    public void onEvent(AppVersionBean.VersionBean map) {
        AppVersionBean.VersionBean updateModelBean = map;
        if (map != null) { //拿到数据判断是否需要更新
            Log.e("personalBean", updateModelBean.getVersion_num());
//            float cur = Float.parseFloat(getAppVersionName(this));
//            float serviceCur = Float.parseFloat(map.getVersion_num());
            if (!getAppVersionName(this).equals(map.getVersion_num())) {
                if (map.getStatus()==1) {//强制更新操作
                    //需要更新
                    // 当前网络状况
                    if (isWifi(this)) {//无线网
                    } else {//流量
                    }
                    if (!isBackground(this)) {
                        Intent serviceIntent = new Intent();
                        serviceIntent.putExtra("updateModel", (Serializable) map);
                        serviceIntent.setAction(BaseMvpActivity.UPDATEVERSION_RECEIVER);
                        sendBroadcast(serviceIntent);
                    } else {
                        Log.e("不发送更新", "不发送更新");
                    }

                } else if (map.getStatus()==0) {
                    //有更新，不强制更新
                    if (!isBackground(this)) {
                        Intent serviceIntent = new Intent();
                        serviceIntent.putExtra("updateModel", (Serializable) map);
                        serviceIntent.setAction(BaseMvpActivity.UPDATEVERSION_RECEIVER);
                        sendBroadcast(serviceIntent);
                    } else {
                        Log.e("不发送更新", "不发送更新");
                    }
                } else {
                    //不需要更新
                    RxToast.info(getResources().getString(R.string.update_no));
                    stopSelf();
                }

            } else {
                //不需要更新
                RxToast.info(getResources().getString(R.string.update_no));
                stopSelf();
            }
        } else {
            RxToast.info(getResources().getString(R.string.update_get_failure));
            stopSelf();
        }
    }

    @Subscribe
    public void onEvent(String myError) {
        RxToast.info(myError);
        stopSelf();
    }

    // 判断当前网络是否为wifi
    public boolean isWifi(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

    /**
     * 返回当前程序版本名
     */
    private String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    private boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    Log.i("后台", appProcess.processName);
                    return true;
                } else {
                    Log.i("前台", appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }
    public int getNetworkType() {
        int netType = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            netType = 1;
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 2;
        }
        return netType;
    }
}
